package io.renren.modules.jxgk.controller;

import io.renren.common.annotation.SysLog;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.modules.jxgk.entity.ElectiveCourseEntity;
import io.renren.modules.jxgk.service.ElectiveCourseService;
import io.renren.modules.jxgk.service.WebSocket;
import io.renren.modules.pullin.DataConversion.TeachControlView;
import io.renren.modules.pullin.entity.BinzhiClassCourse;
import io.renren.modules.pullin.entity.ClassCourse;
import io.renren.modules.pullin.service.PullOutService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("ElectiveCourse/")
public class ElectiveCourseController {

    @Autowired
    ElectiveCourseService electiveCourseService;
    @Autowired
    WebSocket webSocket;
    @Autowired
    PullOutService pullOutService;

    @RequestMapping("Select")
    public R list(@RequestParam Map<String, Object> params){
        //查询列表数据
        Query query = new Query(params);
        List<ElectiveCourseEntity> cse = electiveCourseService.queryList(query);
        int total = electiveCourseService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(cse, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }
    @RequestMapping("/Delete")
    public R delete(@RequestBody String[] indexs){
        electiveCourseService.deleteBatch(indexs);
        return R.ok();
    }
    @RequestMapping("/Insert")
    public R save(@RequestBody ElectiveCourseEntity ste){
        electiveCourseService.save(ste);
        return R.ok();
    }
    @RequestMapping("/Info/{index}")
    public R info(@PathVariable("index") String index){
        ElectiveCourseEntity cse = electiveCourseService.queryObject(index);
        return R.ok().put("ElectiveCourse", cse);
    }
    @SysLog("修改用户")
    @RequestMapping("/Update")
    public R update(@RequestBody ElectiveCourseEntity cse){
        electiveCourseService.update(cse);
        return R.ok();
    }

    /**
     * ------------------------上传文件-------------------------------
     */
    @RequestMapping("/upload")

    //事务如何实现？
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        //这里只写了elx一种，就是excel2003-2007这个版本的， 别用错了
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        //从文件中获取数据
        List<ElectiveCourseEntity> electiveCourseEntities=excelToEntity(file.getInputStream());
        //插入数据库
        insertToDataBase(electiveCourseEntities);
        return R.ok().put("msg", "数据导入成功");
    }

    private void insertToDataBase(List<ElectiveCourseEntity> electiveCourseEntities){
        int i=1;
        int j=1;
        double k=0;
        String errReason;
        String errId;
        String errPos;
        String erresult;
        TeachControlView tcv=new TeachControlView();
        for(ElectiveCourseEntity t:electiveCourseEntities){
            String usr_id=electiveCourseService.queryUserId(t.getStudentId());
            if(usr_id!=null){
                    electiveCourseService.insertUserRole(usr_id,"10");

            }
            List<ElectiveCourseEntity> exist=pullOutService.findElectiveCourseByStudentIdAndCourseTime(t.getStudentId(),t.getCourseTime());
            if(!exist.isEmpty()){//如果存在，删除
                pullOutService.DeleteElectiveCourseByStudentIdAndCourseTime(t.getStudentId(),t.getCourseTime());
                System.out.println("log:数据重复,删除，本条第"+j+"条");
                j++;
            }
            if(t.getCourseTime()!=null){//上课时间为空，数据有误
                try {
                    pullOutService.insertElectiveCourse(t);
                    System.out.println("log:插入数据成功，本条第"+i+"条");
                    i++;

                }catch (Exception e){
                    errReason="错误信息:"+e+"\n";
                    errId="错误ID:"+i+"\n";
                    errPos="错误位置:"+t.getCourseTime()+"\n";
                    erresult=errReason+errId+errPos;
                    tcv.appendMethodB("errInfo.txt",erresult);
                }
            }
            //发送websocket消息
            k++;
            webSocket.sendMessage(""+k/electiveCourseEntities.size()*100);
        }
    }
    private List<ElectiveCourseEntity> excelToEntity(InputStream inputStream) {
        List<ElectiveCourseEntity> electiveCourseEntities=new ArrayList<>();
        HSSFWorkbook wb = null;
        //保存文件信息
        try {
            wb = new HSSFWorkbook(inputStream);
            // logger.debug(wb.getNumberOfSheets());
            HSSFSheet sheet = wb.getSheetAt(0);
            //直接把表头直接加上了，如果数据没错乱的话，可以直接导入。
            for(int i = sheet.getFirstRowNum()+1;i<=sheet.getLastRowNum();i++){
                HSSFRow row = sheet.getRow(i);
                Iterator cells = row.cellIterator();
                //大脑有点当机，想不出更好点的办法了，先这样吧，用循环赋值
                ElectiveCourseEntity temp=new ElectiveCourseEntity();
                electiveCourseEntities.add(temp);
                int j=1;
                while(cells.hasNext()){
                    HSSFCell cell = (HSSFCell) cells.next();
                    String s=cell.toString();
                    if(j==1)
                        temp.setCourseName(s);
                    if(j==2)
                        temp.setCourseId(s);
                    if(j==3)
                        temp.setStudentId(s);
                    if(j==4)
                        temp.setStudentName(s);
                    if(j==5)
                        temp.setTeacherId(s);
                    if(j==6)
                        temp.setTeacherName(s);
                    if(j==7)
                       //temp.setCourseTime(s);
                        temp.setCourseTime("2018-11-11");
                    if(j==8)
                        temp.setCourseWhichIndex(s);
                    if(j==9)
                        temp.setCourseClassroom(s);
                    j++;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return electiveCourseEntities;
    }
}